package com.jl.springbean;

import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class JLFactoryBean<T> implements FactoryBean<T> {

    /**
     * 构建需要使用的参数
     */
    private Class<T> interfaceType;
    private Class<?> implClass;

    public JLFactoryBean(Class<T> interfaceType, Class<?> implClass) {
        this.interfaceType = interfaceType;
        this.implClass = implClass;
    }

    @Override
    public T getObject() throws Exception {
        Constructor<?>[] declaredConstructors = implClass.getDeclaredConstructors();
        Constructor<?> constructor = declaredConstructors[0];
        // 通过构造函数初始化
        return (T) Proxy.newProxyInstance(interfaceType.getClassLoader(), new Class[]{interfaceType}, (InvocationHandler) constructor.newInstance(interfaceType));
    }

    @Override
    public Class<?> getObjectType() {
        // 该方法返回的getObject()方法返回对象的类型,这里是基于interfaceType生成的代理对象,所以类型就是interfaceType
        return interfaceType;
    }

}
